<template>
  <div class="pdf-viewer-container">
    <div class="pdf-controls">
      <button @click="prevPage" :disabled="page === 1">上一页</button>
      <span class="page-info">第 {{ page }} 页 / 共 {{ numPages || '--' }} 页</span>
      <button @click="nextPage" :disabled="page === numPages">下一页</button>
    </div>

    <div class="pdf-viewer">
      <pdf
        ref="pdf"
        :src="pdfSrc"
        :page="page"
        @num-pages="numPages = $event"
        @error="pdfError"
        @link-clicked="handleLinkClick"
      ></pdf>
    </div>
  </div>
</template>

<script>
import pdf from 'vue-pdf'

export default {
  components: {
    pdf
  },
  props: {
    src: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      pdfSrc: null,
      page: 1,
      numPages: 0
    }
  },
  created() {
    this.loadPdf()
  },
  watch: {
    src: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.loadPdf()
        }
      }
    }
  },
  methods: {
    loadPdf() {
      if (typeof this.src === 'string') {
        this.pdfSrc = pdf.createLoadingTask(this.src)
      } else {
        this.pdfSrc = this.src
      }

      this.page = 1

      if (this.pdfSrc) {
        this.pdfSrc.then(pdf => {
          this.numPages = pdf.numPages
        }).catch(error => {
          console.error('PDF加载失败:', error)
        })
      }
    },
    prevPage() {
      if (this.page > 1) this.page--
    },
    nextPage() {
      if (this.page < this.numPages) this.page++
    },
    pdfError(error) {
      console.error('PDF渲染错误:', error)
      this.$emit('error', error)
    },
    handleLinkClick(page) {
      this.page = page
    }
  }
}
</script>

<style scoped>
.pdf-viewer-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
}

.pdf-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  background: #f8f8f8;
  border-bottom: 1px solid #e0e0e0;
}

.pdf-controls button {
  margin: 0 10px;
  padding: 5px 15px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.pdf-controls button:hover {
  background: #0d8aee;
}

.pdf-controls button:disabled {
  background: #b0b0b0;
  cursor: not-allowed;
}

.page-info {
  margin: 0 15px;
  min-width: 100px;
  text-align: center;
  color: #333;
}

.pdf-viewer {
  flex: 1;
  overflow: auto;
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px 0;
}

/* 确保PDF内容居中 */
.pdf-viewer >>> canvas {
  margin: 0 auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #eee;
}
</style>
